using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model;
using WPF_MVVM_Test.Services;

namespace WPF_MVVM_Test.MVVM_ViewModel
{
    /// <summary>
    /// 数据导出页面的ViewModel
    /// 实现鱼塘数据导出功能，包括实时导出和异步任务
    /// </summary>
    public class ExportViewModel : BaseViewModel
    {
        private readonly HttpClient _httpClient;
        private readonly MessageQueueService _messageQueueService;
        private readonly SignalRService _signalRService;
        private const string BaseApiUrl = "http://101.200.57.145:8215/api/Export";
        
        // 防止重复处理的状态管理 - 使用更强的防重复机制
        private readonly HashSet<string> _processedTaskIds = new HashSet<string>();
        private readonly HashSet<string> _downloadingTasks = new HashSet<string>();
        private readonly HashSet<string> _shownNotifications = new HashSet<string>();
        private readonly Dictionary<string, DateTime> _lastProcessedTime = new Dictionary<string, DateTime>();
        private readonly object _stateLock = new object();
        private bool _eventsSubscribed = false;

        /// <summary>
        /// 构造函数
        /// </summary>
        public ExportViewModel()
        {
            _httpClient = new HttpClient();
            _messageQueueService = new MessageQueueService();
            _signalRService = new SignalRService("http://101.200.57.145:8215/fishNotificationHub");
            
            // 初始化集合
            OperationLogs = new ObservableCollection<OperationLog>();
            SupportedFormats = new ObservableCollection<string>();
            
            // 初始化统计数据
            Statistics = new ExportStatistics();
            
            // 创建命令
            ExportFishDataCommand = CreateCommand(ExecuteExportFishData, CanExecuteExport);
            ExportFishTypeDataCommand = CreateCommand(ExecuteExportFishTypeData, CanExecuteExport);
            ExportStatisticsCommand = CreateCommand(ExecuteExportStatistics, CanExecuteExport);
            SubmitAsyncTaskCommand = CreateCommand(ExecuteSubmitAsyncTask, CanExecuteExport);
            GetSupportedFormatsCommand = CreateCommand(ExecuteGetSupportedFormats);
            GetTaskStatusCommand = CreateCommand(ExecuteGetTaskStatus);
            DownloadCurrentTaskCommand = CreateCommand(ExecuteDownloadCurrentTask, CanExecuteDownload);
            ClearLogsCommand = CreateCommand(ExecuteClearLogs);
            TestSignalRCommand = CreateCommand(ExecuteTestSignalR);
            
            // 添加调试命令
            TestApiEndpointsCommand = CreateCommand(ExecuteTestApiEndpoints);
            
            // 初始化MQ连接和消息处理
            InitializeMessageQueue();
            
            // 添加初始日志
            AddLog("🎯 鱼塘数据导出工具已加载", LogLevel.Info);
            AddLog("💡 提示: 请确保ReadAPI服务已启动 (http://101.200.57.145:8215)", LogLevel.Warning);
            
            // 加载支持的格式
            ExecuteGetSupportedFormats();
        }

        #region 属性

        // 鱼塘数据导出参数
        private int? _fishTypeId;
        public int? FishTypeId
        {
            get => _fishTypeId;
            set => SetProperty(ref _fishTypeId, value);
        }

        private int _fishStatus = 0;
        public int FishStatus
        {
            get => _fishStatus;
            set => SetProperty(ref _fishStatus, value);
        }

        private string _fishKeyword = string.Empty;
        public string FishKeyword
        {
            get => _fishKeyword;
            set => SetProperty(ref _fishKeyword, value);
        }

        // 统计报表参数
        private DateTime? _startDate;
        public DateTime? StartDate
        {
            get => _startDate;
            set => SetProperty(ref _startDate, value);
        }

        private DateTime? _endDate;
        public DateTime? EndDate
        {
            get => _endDate;
            set => SetProperty(ref _endDate, value);
        }

        // 异步任务参数
        private string _asyncExportType = "FishData";
        public string AsyncExportType
        {
            get => _asyncExportType;
            set => SetProperty(ref _asyncExportType, value);
        }

        private int _taskPriority = 5;
        public int TaskPriority
        {
            get => _taskPriority;
            set => SetProperty(ref _taskPriority, value);
        }

        // 当前任务信息
        private ExportTask? _currentTask;
        public ExportTask? CurrentTask
        {
            get => _currentTask;
            set
            {
                SetProperty(ref _currentTask, value);
                OnPropertyChanged(nameof(IsCurrentTaskVisible));
                OnPropertyChanged(nameof(CurrentTaskId));
                OnPropertyChanged(nameof(CurrentTaskStatus));
                OnPropertyChanged(nameof(CurrentTaskProgress));
            }
        }

        public bool IsCurrentTaskVisible => CurrentTask != null;
        public string CurrentTaskId => CurrentTask?.TaskId ?? "无";
        public string CurrentTaskStatus => CurrentTask?.Status ?? "无";
        public string CurrentTaskProgress => CurrentTask != null ? $"{CurrentTask.Progress}%" : "0%";

        // 是否正在执行导出操作
        private bool _isExporting;
        public bool IsExporting
        {
            get => _isExporting;
            set => SetProperty(ref _isExporting, value);
        }

        // 统计信息
        private ExportStatistics _statistics = new();
        public ExportStatistics Statistics
        {
            get => _statistics;
            set => SetProperty(ref _statistics, value);
        }

        // 操作日志
        public ObservableCollection<OperationLog> OperationLogs { get; }

        // 支持的导出格式
        public ObservableCollection<string> SupportedFormats { get; }

        // 导出类型选项
        public List<string> ExportTypeOptions { get; } = new() { "FishData", "FishType", "Statistics" };
        
        // 优先级选项
        public List<int> PriorityOptions { get; } = new() { 1, 5, 10 };

        // 鱼塘状态选项
        public Dictionary<int, string> FishStatusOptions { get; } = new()
        {
            { 0, "所有状态" },
            { 1, "正常" },
            { 2, "维护中" },
            { 3, "停用" }
        };

        #endregion

        #region 命令

        public ICommand ExportFishDataCommand { get; }
        public ICommand ExportFishTypeDataCommand { get; }
        public ICommand ExportStatisticsCommand { get; }
        public ICommand SubmitAsyncTaskCommand { get; }
        public ICommand GetSupportedFormatsCommand { get; }
        public ICommand GetTaskStatusCommand { get; }
        public ICommand DownloadCurrentTaskCommand { get; }
        public ICommand ClearLogsCommand { get; }
        public ICommand TestApiEndpointsCommand { get; }
        public ICommand TestSignalRCommand { get; }

        #endregion

        #region 命令执行方法

        private bool CanExecuteExport() => !IsExporting;
        private bool CanExecuteDownload() => CurrentTask != null && CurrentTask.Status == "completed";

        /// <summary>
        /// 导出鱼塘数据
        /// </summary>
        private async void ExecuteExportFishData()
        {
            IsExporting = true;
            try
            {
                Statistics.TotalExports++;
                AddLog("🚀 开始导出鱼塘数据...", LogLevel.Info);

                var parameters = new Dictionary<string, object>();
                if (FishTypeId.HasValue) parameters["fishTypeId"] = FishTypeId.Value;
                if (FishStatus > 0) parameters["status"] = FishStatus;
                if (!string.IsNullOrEmpty(FishKeyword)) parameters["keyword"] = FishKeyword;

                var success = await CallExportApi("ExportFishData", parameters);
                if (success)
                {
                    Statistics.SuccessExports++;
                    AddLog("✅ 鱼塘数据导出成功！", LogLevel.Success);
                }
                else
                {
                    Statistics.FailedExports++;
                    AddLog("❌ 鱼塘数据导出失败", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                Statistics.FailedExports++;
                AddLog($"❌ 导出失败: {ex.Message}", LogLevel.Error);
            }
            finally
            {
                IsExporting = false;
                OnPropertyChanged(nameof(Statistics));
            }
        }

        /// <summary>
        /// 导出鱼塘类型数据
        /// </summary>
        private async void ExecuteExportFishTypeData()
        {
            IsExporting = true;
            try
            {
                Statistics.TotalExports++;
                AddLog("🚀 开始导出鱼塘类型数据...", LogLevel.Info);

                var success = await CallExportApi("ExportFishTypeData", null);
                if (success)
                {
                    Statistics.SuccessExports++;
                    AddLog("✅ 鱼塘类型数据导出成功！", LogLevel.Success);
                }
                else
                {
                    Statistics.FailedExports++;
                    AddLog("❌ 鱼塘类型数据导出失败", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                Statistics.FailedExports++;
                AddLog($"❌ 导出失败: {ex.Message}", LogLevel.Error);
            }
            finally
            {
                IsExporting = false;
                OnPropertyChanged(nameof(Statistics));
            }
        }

        /// <summary>
        /// 导出统计报表
        /// </summary>
        private async void ExecuteExportStatistics()
        {
            IsExporting = true;
            try
            {
                Statistics.TotalExports++;
                AddLog("🚀 开始导出鱼塘统计报表...", LogLevel.Info);

                var parameters = new Dictionary<string, object>();
                if (StartDate.HasValue) parameters["startDate"] = StartDate.Value.ToString("yyyy-MM-dd");
                if (EndDate.HasValue) parameters["endDate"] = EndDate.Value.ToString("yyyy-MM-dd");

                var success = await CallExportApi("ExportFishStatistics", parameters);
                if (success)
                {
                    Statistics.SuccessExports++;
                    AddLog("✅ 鱼塘统计报表导出成功！", LogLevel.Success);
                }
                else
                {
                    Statistics.FailedExports++;
                    AddLog("❌ 鱼塘统计报表导出失败", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                Statistics.FailedExports++;
                AddLog($"❌ 导出失败: {ex.Message}", LogLevel.Error);
            }
            finally
            {
                IsExporting = false;
                OnPropertyChanged(nameof(Statistics));
            }
        }

        /// <summary>
        /// 提交异步导出任务
        /// </summary>
        private async void ExecuteSubmitAsyncTask()
        {
            IsExporting = true;
            try
            {
                AddLog("🚀 提交异步导出任务...", LogLevel.Info);

                var parameters = new Dictionary<string, object>();
                switch (AsyncExportType)
                {
                    case "FishData":
                        if (FishTypeId.HasValue) parameters["fishTypeId"] = FishTypeId.Value;
                        if (FishStatus > 0) parameters["status"] = FishStatus;
                        if (!string.IsNullOrEmpty(FishKeyword)) parameters["keyword"] = FishKeyword;
                        break;
                    case "Statistics":
                        if (StartDate.HasValue) parameters["startDate"] = StartDate.Value.ToString("yyyy-MM-dd");
                        if (EndDate.HasValue) parameters["endDate"] = EndDate.Value.ToString("yyyy-MM-dd");
                        break;
                }

                var request = new ExportRequest
                {
                    ExportType = AsyncExportType,
                    Parameters = parameters,
                    Priority = TaskPriority,
                    Format = "xlsx",
                    EmailNotification = false,
                    EmailAddress = string.Empty
                };

                var json = JsonSerializer.Serialize(request);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync($"{BaseApiUrl}/SubmitExportTask", content);
                if (response.IsSuccessStatusCode)
                {
                    var resultJson = await response.Content.ReadAsStringAsync();
                    AddLog($"🔍 API响应内容: {resultJson}", LogLevel.Info);
                    
                    try
                    {
                        var result = JsonSerializer.Deserialize<ApiResponse<ExportTask>>(resultJson, new JsonSerializerOptions
                        {
                            PropertyNameCaseInsensitive = true
                        });
                        
                        AddLog($"🔍 反序列化结果 - Success: {result?.Success ?? false}", LogLevel.Info);
                        
                        if (result?.Success == true && result.Data != null)
                        {
                            CurrentTask = result.Data;
                            AddLog($"✅ 异步导出任务提交成功！任务ID: {CurrentTask.TaskId}", LogLevel.Success);
                            AddLog($"📊 任务状态: {CurrentTask.Status}, 提交时间: {CurrentTask.SubmittedAt:yyyy-MM-dd HH:mm:ss}", LogLevel.Info);
                            AddLog("✨ 任务已提交到后端处理队列", LogLevel.Info);
                            
                            // 如果SignalR已连接，可选择通知服务器监听此任务
                            if (_signalRService.IsConnected)
                            {
                                try
                                {
                                    AddLog("📡 尝试通知SignalR服务器监听此任务...", LogLevel.Info);
                                    var notifyResult = await _signalRService.SendMessageAsync("MonitorTask", CurrentTask.TaskId);
                                    if (notifyResult)
                                    {
                                        AddLog("✅ SignalR服务器已开始监听任务完成", LogLevel.Success);
                                    }
                                    else
                                    {
                                        AddLog("⚠️ MonitorTask方法调用失败，但SignalR连接正常", LogLevel.Info);
                                        AddLog("💡 任务完成时仍会收到自动推送通知", LogLevel.Info);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    AddLog($"⚠️ MonitorTask调用异常: {ex.Message}", LogLevel.Info);
                                    AddLog("💡 这不影响接收推送通知功能", LogLevel.Info);
                                }
                            }
                            else
                            {
                                AddLog("⚠️ SignalR未连接，将无法收到完成通知", LogLevel.Warning);
                                AddLog("💡 您可以手动点击'查询任务状态'或'测试SignalR'按钮", LogLevel.Info);
                            }
                        }
                        else
                        {
                            AddLog($"❌ 任务提交失败: {result?.Message ?? "未知错误"}", LogLevel.Error);
                            if (result != null)
                            {
                                AddLog($"🔍 响应详情 - Success: {result.Success}", LogLevel.Error);
                            }
                        }
                    }
                    catch (JsonException jsonEx)
                    {
                        AddLog($"❌ JSON反序列化失败: {jsonEx.Message}", LogLevel.Error);
                        AddLog($"🔍 原始响应: {resultJson}", LogLevel.Error);
                    }
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    AddLog($"❌ 任务提交失败: {response.StatusCode} - {response.ReasonPhrase}", LogLevel.Error);
                    AddLog($"🔍 错误详情: {errorContent}", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                AddLog($"❌ 任务提交失败: {ex.Message}", LogLevel.Error);
            }
            finally
            {
                IsExporting = false;
            }
        }

        /// <summary>
        /// 获取支持的导出格式
        /// </summary>
        private async void ExecuteGetSupportedFormats()
        {
            try
            {
                AddLog("🔍 查询支持的导出格式...", LogLevel.Info);

                var response = await _httpClient.GetAsync($"{BaseApiUrl}/GetSupportedFormats");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    AddLog($"📊 API返回数据: {json}", LogLevel.Info);
                    
                    try
                    {
                        // 尝试解析为ExportFormatInfo数组
                        var result = JsonSerializer.Deserialize<ApiResponse<List<ExportFormatInfo>>>(json);
                        
                        if (result?.Data != null)
                        {
                            SupportedFormats.Clear();
                            foreach (var format in result.Data)
                            {
                                SupportedFormats.Add($"{format.Format} - {format.Description}");
                            }
                            AddLog($"📋 支持的导出格式: {string.Join(", ", result.Data.Select(f => f.Format))}", LogLevel.Success);
                        }
                        else
                        {
                            AddLog($"❌ API返回数据为空", LogLevel.Error);
                        }
                    }
                    catch (JsonException jsonEx)
                    {
                        AddLog($"❌ JSON解析失败: {jsonEx.Message}", LogLevel.Error);
                        
                        // 尝试其他解析方式
                        try
                        {
                            // 尝试直接解析为字符串数组
                            var formats = JsonSerializer.Deserialize<List<string>>(json);
                            if (formats != null)
                            {
                                SupportedFormats.Clear();
                                foreach (var format in formats)
                                {
                                    SupportedFormats.Add(format);
                                }
                                AddLog($"📋 支持的导出格式: {string.Join(", ", formats)}", LogLevel.Success);
                            }
                        }
                        catch (Exception fallbackEx)
                        {
                            AddLog($"❌ 所有解析方式都失败: {fallbackEx.Message}", LogLevel.Error);
                            AddLog($"📊 原始数据: {json}", LogLevel.Info);
                            
                            // 添加默认格式以确保程序可用
                            SupportedFormats.Clear();
                            SupportedFormats.Add("xlsx - Excel格式");
                            SupportedFormats.Add("csv - CSV格式");
                            AddLog("📋 使用默认支持格式", LogLevel.Warning);
                        }
                    }
                }
                else
                {
                    AddLog($"❌ HTTP请求失败: {response.StatusCode}", LogLevel.Error);
                    
                    // 添加默认格式
                    SupportedFormats.Clear();
                    SupportedFormats.Add("xlsx - Excel格式");
                    SupportedFormats.Add("csv - CSV格式");
                    AddLog("📋 使用默认支持格式", LogLevel.Warning);
                }
            }
            catch (Exception ex)
            {
                AddLog($"❌ 查询格式失败: {ex.Message}", LogLevel.Error);
                
                // 添加默认格式
                SupportedFormats.Clear();
                SupportedFormats.Add("xlsx - Excel格式");
                SupportedFormats.Add("csv - CSV格式");
                AddLog("📋 使用默认支持格式", LogLevel.Warning);
            }
        }

        /// <summary>
        /// 查询任务状态
        /// </summary>
        private async void ExecuteGetTaskStatus()
        {
            if (CurrentTask == null)
            {
                AddLog("⚠️ 没有当前任务，请先提交一个异步导出任务", LogLevel.Warning);
                return;
            }

            try
            {
                AddLog($"🔍 查询任务状态 - 任务ID: {CurrentTask.TaskId}", LogLevel.Info);

                var response = await _httpClient.GetAsync($"{BaseApiUrl}/GetExportTaskStatus?taskId={CurrentTask.TaskId}");
                if (response.IsSuccessStatusCode)
                {
                    var json = await response.Content.ReadAsStringAsync();
                    AddLog($"📊 API返回数据: {json}", LogLevel.Info);
                    
                    try
                    {
                        var result = JsonSerializer.Deserialize<ApiResponse<ExportTask>>(json);
                        
                        if (result?.Success == true && result.Data != null)
                        {
                            CurrentTask = result.Data;
                            AddLog($"📊 任务状态: {CurrentTask.Status} ({CurrentTask.Progress}%)", LogLevel.Success);
                            AddLog($"   消息: {CurrentTask.Message}", LogLevel.Info);
                            if (!string.IsNullOrEmpty(CurrentTask.FileSize) && CurrentTask.FileSize != "0")
                            {
                                AddLog($"   文件大小: {CurrentTask.FileSize}", LogLevel.Info);
                            }
                        }
                        else
                        {
                            AddLog($"❌ API返回失败: {result?.Message}", LogLevel.Error);
                        }
                    }
                    catch (JsonException jsonEx)
                    {
                        AddLog($"❌ JSON解析失败: {jsonEx.Message}", LogLevel.Error);
                        AddLog($"📊 原始数据: {json}", LogLevel.Info);
                    }
                }
                else
                {
                    AddLog($"❌ HTTP请求失败: {response.StatusCode}", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                AddLog($"❌ 查询失败: {ex.Message}", LogLevel.Error);
            }
        }

        /// <summary>
        /// 下载当前任务文件
        /// </summary>
        private async void ExecuteDownloadCurrentTask()
        {
            if (CurrentTask == null)
            {
                AddLog("⚠️ 没有当前任务", LogLevel.Warning);
                return;
            }

            try
            {
                AddLog($"📁 下载任务文件 - 任务ID: {CurrentTask.TaskId}", LogLevel.Info);

                // URL编码任务ID以防特殊字符问题
                var encodedTaskId = Uri.EscapeDataString(CurrentTask.TaskId);
                var downloadUrl = $"{BaseApiUrl}/DownloadFile?taskId={encodedTaskId}";
                
                AddLog($"🔗 下载URL: {downloadUrl}", LogLevel.Info);

                // 创建带有正确Accept头的请求
                using var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl);
                request.Headers.Add("Accept", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                
                AddLog($"📋 请求头: Accept = application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", LogLevel.Info);

                var response = await _httpClient.SendAsync(request);
                
                AddLog($"📊 HTTP状态码: {response.StatusCode}", LogLevel.Info);
                
                if (response.IsSuccessStatusCode)
                {
                    var fileBytes = await response.Content.ReadAsByteArrayAsync();
                    var fileName = CurrentTask.FileName ?? $"export_{CurrentTask.TaskId}.xlsx";
                    
                    AddLog($"📦 文件大小: {fileBytes.Length / 1024.0:F1} KB", LogLevel.Info);
                    
                    // 获取用户的下载文件夹路径
                    var downloadsPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
                    var fullFilePath = System.IO.Path.Combine(downloadsPath, fileName);
                    
                    // 使用统一的文件名生成逻辑
                    var uniqueFileName = GenerateUniqueFileName(fileName, downloadsPath);
                    fileName = uniqueFileName;
                    fullFilePath = System.IO.Path.Combine(downloadsPath, fileName);
                    
                    // 确保下载目录存在
                    System.IO.Directory.CreateDirectory(downloadsPath);
                    
                    // 保存文件
                    await System.IO.File.WriteAllBytesAsync(fullFilePath, fileBytes);
                    
                    // 更新统计信息
                    Statistics.SuccessExports++;
                    Statistics.TotalSize += fileBytes.Length;
                    
                    AddLog($"✅ 文件下载成功！", LogLevel.Success);
                    AddLog($"   文件名: {fileName}", LogLevel.Info);
                    AddLog($"   大小: {fileBytes.Length / 1024.0:F1} KB", LogLevel.Info);
                    AddLog($"   保存位置: {fullFilePath}", LogLevel.Info);
                    
                    // 使用防重复的弹框显示方法
                    ShowDownloadCompleteDialog(fullFilePath, CurrentTask?.TaskId ?? "manual_download");
                }
                else
                {
                    // 读取错误响应内容
                    var errorContent = await response.Content.ReadAsStringAsync();
                    AddLog($"❌ 下载失败: {response.StatusCode}", LogLevel.Error);
                    AddLog($"❌ 错误详情: {errorContent}", LogLevel.Error);
                    
                    // 如果仍然是BadRequest，尝试其他Content-Type
                    if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        AddLog("🔄 尝试使用其他Accept头...", LogLevel.Info);
                        await TryAlternativeAcceptHeaders();
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"❌ 下载失败: {ex.Message}", LogLevel.Error);
            }
            finally
            {
                OnPropertyChanged(nameof(Statistics));
            }
        }

        /// <summary>
        /// 尝试使用其他Accept头进行下载
        /// </summary>
        private async Task TryAlternativeAcceptHeaders()
        {
            if (CurrentTask == null) return;

            var acceptHeaders = new[]
            {
                "application/octet-stream",
                "application/vnd.ms-excel",
                "application/excel",
                "*/*",
                "text/csv",
                "application/json"
            };

            var encodedTaskId = Uri.EscapeDataString(CurrentTask.TaskId);
            var downloadUrl = $"{BaseApiUrl}/DownloadFile?taskId={encodedTaskId}";

            foreach (var acceptHeader in acceptHeaders)
            {
                try
                {
                    AddLog($"🔄 尝试Accept头: {acceptHeader}", LogLevel.Info);
                    
                    using var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl);
                    request.Headers.Add("Accept", acceptHeader);
                    
                    var response = await _httpClient.SendAsync(request);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        var fileBytes = await response.Content.ReadAsByteArrayAsync();
                        
                        if (fileBytes.Length > 0)
                        {
                            AddLog($"✅ 成功使用Accept头: {acceptHeader}", LogLevel.Success);
                            
                            var fileName = CurrentTask.FileName ?? $"export_{CurrentTask.TaskId}.xlsx";
                            var downloadsPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
                            var fullFilePath = System.IO.Path.Combine(downloadsPath, fileName);
                            
                            System.IO.Directory.CreateDirectory(downloadsPath);
                            await System.IO.File.WriteAllBytesAsync(fullFilePath, fileBytes);
                            
                            Statistics.SuccessExports++;
                            Statistics.TotalSize += fileBytes.Length;
                            
                            AddLog($"✅ 文件下载成功！保存位置: {fullFilePath}", LogLevel.Success);
                            return;
                        }
                    }
                    else
                    {
                        AddLog($"   失败: {response.StatusCode}", LogLevel.Warning);
                    }
                }
                catch (Exception ex)
                {
                    AddLog($"   错误: {ex.Message}", LogLevel.Warning);
                }
                
                await Task.Delay(200);
            }
            
            AddLog("❌ 所有Accept头都尝试失败", LogLevel.Error);
        }

        /// <summary>
        /// 尝试其他下载方式
        /// </summary>
        private async Task TryAlternativeDownload()
        {
            if (CurrentTask == null) return;

            try
            {
                // 根据已知的API结构，尝试更合理的接口路径
                var alternativeUrls = new[]
                {
                    $"{BaseApiUrl}/DownloadExportFile?taskId={Uri.EscapeDataString(CurrentTask.TaskId)}",
                    $"{BaseApiUrl}/GetExportFile?taskId={Uri.EscapeDataString(CurrentTask.TaskId)}",
                    $"{BaseApiUrl}/DownloadTaskFile?taskId={Uri.EscapeDataString(CurrentTask.TaskId)}",
                    $"http://101.200.57.145:8215/api/Export/Download/{Uri.EscapeDataString(CurrentTask.TaskId)}",
                    $"http://101.200.57.145:8215/api/File/Export?taskId={Uri.EscapeDataString(CurrentTask.TaskId)}",
                    $"http://101.200.57.145:8215/api/Download/File?taskId={Uri.EscapeDataString(CurrentTask.TaskId)}",
                    $"http://101.200.57.145:8215/api/Export/File?taskId={Uri.EscapeDataString(CurrentTask.TaskId)}"
                };

                foreach (var url in alternativeUrls)
                {
                    AddLog($"🔄 尝试URL: {url}", LogLevel.Info);
                    
                    try
                    {
                        var response = await _httpClient.GetAsync(url);
                        AddLog($"📊 状态码: {response.StatusCode}", LogLevel.Info);
                        
                        if (response.IsSuccessStatusCode)
                        {
                            AddLog($"✅ 成功找到可用的下载接口: {url}", LogLevel.Success);
                            
                            var fileBytes = await response.Content.ReadAsByteArrayAsync();
                            
                            // 检查是否真的是文件内容
                            if (fileBytes.Length > 0)
                            {
                                var fileName = CurrentTask.FileName ?? $"export_{CurrentTask.TaskId}.xlsx";
                                
                                var downloadsPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
                                var fullFilePath = System.IO.Path.Combine(downloadsPath, fileName);
                                
                                System.IO.Directory.CreateDirectory(downloadsPath);
                                await System.IO.File.WriteAllBytesAsync(fullFilePath, fileBytes);
                                
                                Statistics.SuccessExports++;
                                Statistics.TotalSize += fileBytes.Length;
                                
                                AddLog($"✅ 文件下载成功！", LogLevel.Success);
                                AddLog($"   文件名: {fileName}", LogLevel.Info);
                                AddLog($"   大小: {fileBytes.Length / 1024.0:F1} KB", LogLevel.Info);
                                AddLog($"   保存位置: {fullFilePath}", LogLevel.Info);
                                return;
                            }
                            else
                            {
                                AddLog($"⚠️ 响应为空，继续尝试其他接口", LogLevel.Warning);
                            }
                        }
                        else
                        {
                            var errorContent = await response.Content.ReadAsStringAsync();
                            AddLog($"❌ 失败: {response.StatusCode} - {errorContent}", LogLevel.Warning);
                        }
                    }
                    catch (Exception ex)
                    {
                        AddLog($"❌ 失败: {ex.Message}", LogLevel.Warning);
                    }
                    
                    // 添加短暂延迟避免过快请求
                    await Task.Delay(200);
                }
                
                AddLog("❌ 所有下载方式都失败了", LogLevel.Error);
                AddLog("💡 建议：请检查服务器端是否提供文件下载接口", LogLevel.Info);
                AddLog("💡 可能的原因：", LogLevel.Info);
                AddLog("   1. 任务尚未完成，文件还未生成", LogLevel.Info);
                AddLog("   2. 服务器端下载接口路径不同", LogLevel.Info);
                AddLog("   3. 需要特殊的认证或参数", LogLevel.Info);
            }
            catch (Exception ex)
            {
                AddLog($"❌ 备用下载失败: {ex.Message}", LogLevel.Error);
            }
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        private void ExecuteClearLogs()
        {
            OperationLogs.Clear();
        }

        /// <summary>
        /// 测试SignalR连接状态
        /// </summary>
        private async void ExecuteTestSignalR()
        {
            try
            {
                AddLog("🔍 开始SignalR诊断测试...", LogLevel.Info);
                AddLog($"📊 当前连接状态: {(_signalRService.IsConnected ? "已连接" : "未连接")}", LogLevel.Info);
                
                if (_signalRService.IsConnected)
                {
                    AddLog($"🆔 连接ID: {_signalRService.ConnectionId}", LogLevel.Info);
                    
                    // 测试发送消息（可选，如果后端支持Ping）
                    AddLog("📡 测试发送Ping消息...", LogLevel.Info);
                    try
                    {
                        var testResult = await _signalRService.SendMessageAsync("Ping", "diagnostic_test");
                        AddLog($"📡 Ping发送结果: {(testResult ? "成功" : "失败 (后端可能未实现Ping方法)")}", testResult ? LogLevel.Success : LogLevel.Info);
                    }
                    catch (Exception ex)
                    {
                        AddLog($"📡 Ping发送异常: {ex.Message} (这是正常的，如果后端未实现Ping)", LogLevel.Info);
                    }
                    
                    // 测试加入组
                    AddLog("👥 测试重新加入通知组...", LogLevel.Info);
                    var joinResult = await _signalRService.JoinUserGroupAsync("demo-user-001");
                    AddLog($"👥 加入组结果: {(joinResult ? "成功" : "失败")}", joinResult ? LogLevel.Success : LogLevel.Error);
                }
                else
                {
                    AddLog("🔄 尝试不同SignalR Hub路径...", LogLevel.Info);
                    await TryDifferentHubPaths();
                }
            }
            catch (Exception ex)
            {
                AddLog($"❌ SignalR诊断测试失败: {ex.Message}", LogLevel.Error);
            }
        }

        /// <summary>
        /// 尝试不同的SignalR Hub路径
        /// </summary>
        private async Task TryDifferentHubPaths()
        {
            var hubPaths = new[]
            {
                "/fishNotificationHub",  // 正确的路径
                "/hub/export",
                "/hubs/export", 
                "/signalr/export",
                "/api/hub/export",
                "/exportHub",
                "/hub",
                "/signalr"
            };

            foreach (var path in hubPaths)
            {
                try
                {
                    var hubUrl = $"http://101.200.57.145:8215{path}";
                    AddLog($"🔄 尝试连接: {hubUrl}", LogLevel.Info);
                    
                    var testService = new SignalRService(hubUrl);
                    var connected = await testService.ConnectAsync();
                    
                    if (connected)
                    {
                        AddLog($"✅ 找到正确的Hub路径: {hubUrl}", LogLevel.Success);
                        AddLog($"🆔 连接ID: {testService.ConnectionId}", LogLevel.Success);
                        
                        // 更新主要服务的Hub地址
                        await _signalRService.DisconnectAsync();
                        _signalRService.Dispose();
                        
                        // 这里理想情况下应该重新创建服务，但为了简化，我们先显示结果
                        AddLog("💡 请联系开发人员更新Hub地址配置", LogLevel.Info);
                        
                        await testService.DisconnectAsync();
                        return;
                    }
                    else
                    {
                        AddLog($"❌ {path} 连接失败", LogLevel.Warning);
                    }
                }
                catch (Exception ex)
                {
                    AddLog($"❌ {path} 异常: {ex.Message}", LogLevel.Warning);
                }
            }
            
            AddLog("❌ 所有Hub路径都无法连接", LogLevel.Error);
            await DiagnoseSignalRConnection();
        }

        /// <summary>
        /// 诊断SignalR连接问题
        /// </summary>
        private async Task DiagnoseSignalRConnection()
        {
            AddLog("🔍 正在诊断SignalR连接问题...", LogLevel.Info);
            
            try
            {
                // 1. 测试网络连接
                AddLog("1️⃣ 测试网络连接...", LogLevel.Info);
                using var client = new HttpClient();
                client.Timeout = TimeSpan.FromSeconds(10);
                
                try
                {
                    // 测试Hub服务器的HTTP连接
                    var hubHost = "http://101.200.57.145:8215";
                    var response = await client.GetAsync($"{hubHost}/health"); // 假设有健康检查端点
                    AddLog($"   HTTP连接测试: {response.StatusCode}", LogLevel.Info);
                }
                catch (Exception ex)
                {
                    AddLog($"   ❌ HTTP连接失败: {ex.Message}", LogLevel.Error);
                    
                    // 尝试ping服务器
                    AddLog("2️⃣ 尝试ping服务器...", LogLevel.Info);
                    try
                    {
                        var ping = new System.Net.NetworkInformation.Ping();
                        var reply = await ping.SendPingAsync("101.200.57.145", 5000);
                        AddLog($"   Ping结果: {reply.Status} ({reply.RoundtripTime}ms)", 
                               reply.Status == System.Net.NetworkInformation.IPStatus.Success ? LogLevel.Success : LogLevel.Error);
                    }
                    catch (Exception pingEx)
                    {
                        AddLog($"   ❌ Ping失败: {pingEx.Message}", LogLevel.Error);
                    }
                }
                
                // 3. 检查防火墙/端口
                AddLog("3️⃣ 检查端口连接...", LogLevel.Info);
                try
                {
                    using var tcpClient = new System.Net.Sockets.TcpClient();
                    await tcpClient.ConnectAsync("101.200.57.145", 8215);
                    AddLog("   ✅ TCP端口8215连接成功", LogLevel.Success);
                    tcpClient.Close();
                }
                catch (Exception tcpEx)
                {
                    AddLog($"   ❌ TCP端口8215连接失败: {tcpEx.Message}", LogLevel.Error);
                    AddLog("   💡 可能是防火墙阻止了连接或服务未运行", LogLevel.Warning);
                }
                
                // 4. 建议解决方案
                AddLog("💡 解决建议:", LogLevel.Info);
                AddLog("   • 确认SignalR Hub服务正在运行", LogLevel.Info);
                AddLog("   • 检查防火墙设置是否允许端口8215", LogLevel.Info);
                AddLog("   • 确认Hub地址是否正确", LogLevel.Info);
                AddLog("   • 如果使用代理，请配置代理设置", LogLevel.Info);
                AddLog("   • 联系后端开发人员确认Hub配置", LogLevel.Info);
                
            }
            catch (Exception ex)
            {
                AddLog($"❌ 诊断过程异常: {ex.Message}", LogLevel.Error);
            }
        }

        /// <summary>
        /// 测试API端点以找到正确的下载接口
        /// </summary>
        private async void ExecuteTestApiEndpoints()
        {
            if (CurrentTask == null)
            {
                AddLog("⚠️ 没有当前任务，无法测试下载接口", LogLevel.Warning);
                return;
            }

            AddLog("🔍 开始测试API端点，寻找正确的下载接口...", LogLevel.Info);
            
            // 测试常见的API端点结构
            var testEndpoints = new[]
            {
                // Swagger/OpenAPI 常见端点
                "http://101.200.57.145:8215/swagger",
                "http://101.200.57.145:8215/swagger/index.html",
                "http://101.200.57.145:8215/api",
                "http://101.200.57.145:8215/api/swagger",
                
                // 常见的下载端点
                $"http://101.200.57.145:8215/api/Export/GetTaskFile/{Uri.EscapeDataString(CurrentTask.TaskId)}",
                $"http://101.200.57.145:8215/api/Export/{Uri.EscapeDataString(CurrentTask.TaskId)}/download",
                $"http://101.200.57.145:8215/api/Files/{Uri.EscapeDataString(CurrentTask.TaskId)}",
                $"http://101.200.57.145:8215/download/{Uri.EscapeDataString(CurrentTask.TaskId)}",
                $"http://101.200.57.145:8215/files/{Uri.EscapeDataString(CurrentTask.TaskId)}",
                
                // 其他可能的端点
                $"http://101.200.57.145:8215/api/Export/DownloadResult?taskId={Uri.EscapeDataString(CurrentTask.TaskId)}",
                $"http://101.200.57.145:8215/api/Task/{Uri.EscapeDataString(CurrentTask.TaskId)}/file"
            };

            foreach (var endpoint in testEndpoints)
            {
                try
                {
                    AddLog($"🔍 测试: {endpoint}", LogLevel.Info);
                    
                    var response = await _httpClient.GetAsync(endpoint);
                    var contentType = response.Content.Headers.ContentType?.MediaType ?? "unknown";
                    var contentLength = response.Content.Headers.ContentLength ?? 0;
                    
                    AddLog($"   状态: {response.StatusCode}, 类型: {contentType}, 大小: {contentLength}", LogLevel.Info);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        if (contentType.Contains("application/") || contentType.Contains("text/html"))
                        {
                            // 可能是文件或API文档
                            var content = await response.Content.ReadAsStringAsync();
                            if (content.Length < 1000) // 如果内容较短，显示出来
                            {
                                AddLog($"   内容预览: {content.Substring(0, Math.Min(200, content.Length))}...", LogLevel.Info);
                            }
                            
                            if (contentType.Contains("excel") || contentType.Contains("spreadsheet") || 
                                endpoint.Contains("download") || endpoint.Contains("file"))
                            {
                                AddLog($"✅ 可能的下载接口: {endpoint}", LogLevel.Success);
                            }
                        }
                    }
                    
                    await Task.Delay(300); // 避免请求过快
                }
                catch (Exception ex)
                {
                    AddLog($"   错误: {ex.Message}", LogLevel.Warning);
                }
            }
            
            AddLog("🔍 API端点测试完成", LogLevel.Info);
        }

        #endregion

        #region 私有方法

        /// <summary>
        /// 通用的导出API调用方法
        /// </summary>
        private async Task<bool> CallExportApi(string endpoint, Dictionary<string, object>? parameters)
        {
            try
            {
                var url = $"{BaseApiUrl}/{endpoint}";
                if (parameters != null && parameters.Any())
                {
                    var queryString = string.Join("&", parameters.Select(p => $"{p.Key}={p.Value}"));
                    url += "?" + queryString;
                }

                var response = await _httpClient.GetAsync(url);
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 添加操作日志
        /// </summary>
        private void AddLog(string message, LogLevel level = LogLevel.Info)
        {
            Application.Current?.Dispatcher.Invoke(() =>
            {
                OperationLogs.Add(new OperationLog
                {
                    Message = message,
                    Level = level,
                    Timestamp = DateTime.Now
                });

                // 保持日志数量在合理范围内
                while (OperationLogs.Count > 100)
                {
                    OperationLogs.RemoveAt(0);
                }
            });
        }

        /// <summary>
        /// 初始化消息队列 - 使用真实的SignalR连接
        /// </summary>
        private async void InitializeMessageQueue()
        {
            try
            {
                // 使用真实的SignalR连接
                AddLog("🔄 正在连接SignalR Hub...", LogLevel.Info);
                AddLog($"🔗 Hub地址: http://101.200.57.145:8215/fishNotificationHub", LogLevel.Info);
                
                // 防止重复订阅事件
                if (!_eventsSubscribed)
                {
                    _signalRService.ExportCompleted += OnExportCompleted;
                    _signalRService.NotificationReceived += OnNotificationReceived;
                    _signalRService.ConnectionStateChanged += OnConnectionStateChanged;
                    _eventsSubscribed = true;
                }
                
                var connected = await _signalRService.ConnectAsync();
                
                if (connected)
                {
                    AddLog($"✅ SignalR连接成功！连接ID: {_signalRService.ConnectionId}", LogLevel.Success);
                    
                    // 加入用户组以接收通知 - 使用与前端测试页面相同的用户ID
                    var joined = await _signalRService.JoinUserGroupAsync("demo-user-001");
                    if (joined)
                    {
                        AddLog("👥 已加入导出通知组 (demo-user-001)", LogLevel.Info);
                        
                        // 测试连接是否真的工作
                        AddLog("🧪 SignalR连接已就绪，可以接收通知", LogLevel.Success);
                        
                        // 可选：测试Ping（如果后端支持）
                        try
                        {
                            var pingResult = await _signalRService.SendMessageAsync("Ping", "connection_test");
                            if (pingResult)
                            {
                                AddLog($"📡 Ping测试结果: 成功", LogLevel.Success);
                            }
                            else
                            {
                                AddLog($"📡 Ping测试结果: 失败 (后端可能未实现Ping方法，但连接正常)", LogLevel.Info);
                            }
                        }
                        catch (Exception ex)
                        {
                            AddLog($"📡 Ping测试异常: {ex.Message} (连接仍然正常)", LogLevel.Info);
                        }
                    }
                    else
                    {
                        AddLog("⚠️ 加入通知组失败", LogLevel.Warning);
                    }
                }
                else
                {
                    AddLog("❌ SignalR连接失败，请检查以下问题:", LogLevel.Error);
                    AddLog("   1. 网络连接是否正常", LogLevel.Info);
                    AddLog("   2. SignalR Hub服务是否启动", LogLevel.Info);
                    AddLog("   3. Hub地址是否正确", LogLevel.Info);
                    AddLog("   4. 防火墙是否阻止连接", LogLevel.Info);
                    
                    // 重要：SignalR失败时不要启用备用MQ，避免双重订阅
                    AddLog("⚠️ 将只使用手动查询方式", LogLevel.Warning);
                }
            }
            catch (Exception ex)
            {
                AddLog($"❌ SignalR连接异常: {ex.Message}", LogLevel.Error);
                AddLog($"🔍 异常详情: {ex}", LogLevel.Error);
                AddLog("⚠️ 将只使用手动查询方式", LogLevel.Warning);
            }
        }

        /// <summary>
        /// SignalR连接状态变化处理
        /// </summary>
        private void OnConnectionStateChanged(object? sender, bool isConnected)
        {
            if (isConnected)
            {
                AddLog("🔗 SignalR连接已恢复", LogLevel.Success);
            }
            else
            {
                AddLog("⚠️ SignalR连接已断开，正在尝试重连...", LogLevel.Warning);
            }
        }

        /// <summary>
        /// 初始化备用消息队列（模拟MQ）- 已禁用以防止双重订阅
        /// </summary>
        private async Task InitializeFallbackMessageQueue()
        {
            // 禁用备用MQ以防止与SignalR双重订阅导致重复处理
            AddLog("⚠️ 备用MQ已禁用，避免双重事件订阅", LogLevel.Warning);
            return;
            
            /*
            try
            {
                _messageQueueService.ExportCompleted += OnExportCompleted;
                _messageQueueService.NotificationReceived += OnNotificationReceived;
                _messageQueueService.StartListening();
                AddLog("🔗 模拟MQ连接已建立，支持自动下载", LogLevel.Success);
            }
            catch (Exception ex)
            {
                AddLog($"❌ 模拟MQ连接失败: {ex.Message}", LogLevel.Error);
                AddLog("⚠️ 将使用轮询方式查询任务状态", LogLevel.Warning);
            }
            */
        }

        /// <summary>
        /// 处理通用通知
        /// </summary>
        private void OnNotificationReceived(object? sender, string message)
        {
            AddLog($"📢 收到通知: {message}", LogLevel.Info);
        }

        /// <summary>
        /// 处理导出完成通知
        /// </summary>
        private async void OnExportCompleted(object? sender, ExportNotification notification)
        {
            // 记录事件来源
            var senderType = sender?.GetType().Name ?? "Unknown";
            var timestamp = DateTime.Now;
            AddLog($"📨 收到导出完成事件 - 来源: {senderType}, 任务ID: {notification.TaskId}, 时间: {timestamp:HH:mm:ss.fff}", LogLevel.Info);
            
            // 使用多重防重复检查
            var taskId = notification.TaskId;
            var fileName = notification.FileName ?? "";
            var baseKey = $"{taskId}_{fileName}";
            
            lock (_stateLock)
            {
                // 检查1: 是否在短时间内重复处理同一任务
                if (_lastProcessedTime.ContainsKey(baseKey))
                {
                    var timeDiff = timestamp - _lastProcessedTime[baseKey];
                    if (timeDiff.TotalSeconds < 5) // 5秒内的重复请求直接忽略
                    {
                        AddLog($"⚠️ 检测到短时间内重复事件 - 任务: {baseKey}, 时间差: {timeDiff.TotalMilliseconds}ms", LogLevel.Warning);
                        AddLog($"   来源: {senderType}, 直接忽略", LogLevel.Warning);
                        return;
                    }
                }
                
                // 检查2: 是否已经处理过该任务
                var uniqueKey = $"{baseKey}_{notification.Timestamp:yyyyMMddHHmmss}";
                if (_processedTaskIds.Contains(uniqueKey))
                {
                    AddLog($"⚠️ 任务已处理过 - 唯一标识: {uniqueKey}", LogLevel.Warning);
                    AddLog($"   来源: {senderType}, 跳过重复处理", LogLevel.Warning);
                    return;
                }
                
                // 检查3: 是否正在下载中
                if (_downloadingTasks.Contains(taskId))
                {
                    AddLog($"⚠️ 任务正在下载中 - 任务ID: {taskId}", LogLevel.Warning);
                    AddLog($"   来源: {senderType}, 跳过重复下载", LogLevel.Warning);
                    return;
                }
                
                // 标记为已处理
                _processedTaskIds.Add(uniqueKey);
                _lastProcessedTime[baseKey] = timestamp;
                _downloadingTasks.Add(taskId);
                
                AddLog($"✅ 任务通过所有重复检查 - 唯一标识: {uniqueKey}", LogLevel.Info);
            }
            
            try
            {
                AddLog($"🎉 开始处理导出完成通知: {notification.Message}", LogLevel.Success);
                AddLog($"📄 任务ID: {notification.TaskId}", LogLevel.Info);
                AddLog($"📁 文件名: {notification.FileName}", LogLevel.Info);
                AddLog($"⏰ 完成时间: {notification.Timestamp:yyyy-MM-dd HH:mm:ss}", LogLevel.Info);
                
                // 更新当前任务状态
                if (CurrentTask != null && CurrentTask.TaskId == notification.TaskId)
                {
                    CurrentTask.Status = notification.Status;
                    CurrentTask.Message = notification.Message;
                    CurrentTask.FileName = notification.FileName;
                    CurrentTask.Progress = 100;
                    CurrentTask.CompletedAt = notification.Timestamp;
                    OnPropertyChanged(nameof(CurrentTask));
                    AddLog("📊 当前任务状态已更新", LogLevel.Info);
                }

                // 更新统计信息（只更新一次）
                Statistics.TotalExports++;
                if (notification.Status.Equals("completed", StringComparison.OrdinalIgnoreCase))
                {
                    Statistics.SuccessExports++;
                    AddLog("📈 成功统计 +1", LogLevel.Info);
                }
                else
                {
                    Statistics.FailedExports++;
                    AddLog("📈 失败统计 +1", LogLevel.Info);
                }

                // 执行自动下载（如果启用）
                if (notification.AutoDownload && !string.IsNullOrEmpty(notification.DownloadUrl))
                {
                    AddLog("🔄 开始自动下载文件...", LogLevel.Info);
                    
                    try
                    {
                        await AutoDownloadFile(notification);
                        AddLog("✅ 自动下载流程完成", LogLevel.Success);
                    }
                    catch (Exception ex)
                    {
                        AddLog($"❌ 自动下载失败: {ex.Message}", LogLevel.Error);
                        AddLog("💡 请使用手动下载功能", LogLevel.Info);
                    }
                }
                else
                {
                    AddLog("💡 您可以点击'下载当前任务'按钮下载文件", LogLevel.Info);
                }
                
                AddLog($"🏁 导出完成通知处理结束 - 任务ID: {notification.TaskId}", LogLevel.Success);
            }
            finally
            {
                // 清空下载标记
                lock (_stateLock)
                {
                    _downloadingTasks.Remove(taskId);
                    AddLog($"🔄 移除任务 {taskId} 的下载标记", LogLevel.Info);
                }
            }
        }

        /// <summary>
        /// 自动下载文件
        /// </summary>
        private async Task AutoDownloadFile(ExportNotification notification)
        {
            try
            {
                string downloadUrl;
                
                if (notification.DownloadUrl.StartsWith("http"))
                {
                    // 如果已经是完整URL，直接使用
                    downloadUrl = notification.DownloadUrl;
                }
                else if (notification.DownloadUrl.StartsWith("/api/Export/"))
                {
                    // 如果是完整的API路径，只需要添加基础URL
                    downloadUrl = $"http://101.200.57.145:8215{notification.DownloadUrl}";
                }
                else
                {
                    // 如果是相对路径，添加完整的API前缀
                    var cleanUrl = notification.DownloadUrl.TrimStart('/');
                    downloadUrl = $"http://101.200.57.145:8215/api/Export/{cleanUrl}";
                }
                
                AddLog($"🔗 下载URL: {downloadUrl}", LogLevel.Info);
                
                var response = await _httpClient.GetAsync(downloadUrl);
                if (response.IsSuccessStatusCode)
                {
                    var fileBytes = await response.Content.ReadAsByteArrayAsync();
                    
                    // 获取用户的下载文件夹路径
                    var downloadsPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Downloads");
                    var fileName = notification.FileName ?? $"export_{notification.TaskId}.xlsx";
                    
                    // 使用统一的文件名生成逻辑
                    var uniqueFileName = GenerateUniqueFileName(fileName, downloadsPath);
                    var fullFilePath = System.IO.Path.Combine(downloadsPath, uniqueFileName);
                    
                    // 确保下载目录存在
                    System.IO.Directory.CreateDirectory(downloadsPath);
                    
                    // 保存文件
                    await System.IO.File.WriteAllBytesAsync(fullFilePath, fileBytes);
                    
                    Statistics.TotalSize += fileBytes.Length;
                    
                    AddLog($"✅ 文件自动下载成功！", LogLevel.Success);
                    AddLog($"   文件名: {uniqueFileName}", LogLevel.Info);
                    AddLog($"   大小: {fileBytes.Length / 1024.0:F1} KB", LogLevel.Info);
                    AddLog($"   位置: {fullFilePath}", LogLevel.Info);
                    
                    // 使用防重复的弹框显示方法
                    ShowDownloadCompleteDialog(fullFilePath, notification.TaskId);
                }
                else
                {
                    AddLog($"❌ 自动下载失败: {response.StatusCode}", LogLevel.Error);
                }
            }
            catch (Exception ex)
            {
                AddLog($"❌ 自动下载异常: {ex.Message}", LogLevel.Error);
                throw;
            }
        }

        #endregion
        
        #region 辅助方法

        /// <summary>
        /// 生成唯一文件名，避免重复
        /// </summary>
        private string GenerateUniqueFileName(string originalFileName, string directory)
        {
            var fullPath = System.IO.Path.Combine(directory, originalFileName);
            if (!System.IO.File.Exists(fullPath))
                return originalFileName;

            var nameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(originalFileName);
            var extension = System.IO.Path.GetExtension(originalFileName);
            var counter = 1;

            string newFileName;
            do
            {
                newFileName = $"{nameWithoutExt}_{counter:D3}{extension}";
                fullPath = System.IO.Path.Combine(directory, newFileName);
                counter++;
            } while (System.IO.File.Exists(fullPath));

            return newFileName;
        }
        
        /// <summary>
        /// 显示下载完成对话框，防止重复显示
        /// </summary>
        private void ShowDownloadCompleteDialog(string filePath, string taskId)
        {
            // 使用文件路径作为更准确的去重标识
            var dialogKey = $"{taskId}_{System.IO.Path.GetFileName(filePath)}";
            
            lock (_stateLock)
            {
                if (_shownNotifications.Contains(dialogKey))
                {
                    AddLog($"⚠️ 下载完成对话框已显示过 - 标识: {dialogKey}", LogLevel.Info);
                    return;
                }
                _shownNotifications.Add(dialogKey);
                AddLog($"✅ 显示下载完成对话框 - 标识: {dialogKey}", LogLevel.Info);
            }
            
            var result = MessageBox.Show($"文件已下载到：\n{filePath}\n\n是否打开文件夹？", 
                                        "下载完成", 
                                        MessageBoxButton.YesNo, 
                                        MessageBoxImage.Question);
            
            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{filePath}\"");
                    AddLog("📂 已打开文件夹", LogLevel.Info);
                }
                catch (Exception ex)
                {
                    AddLog($"⚠️ 无法打开文件夹: {ex.Message}", LogLevel.Warning);
                }
            }
            else
            {
                AddLog("📁 用户选择不打开文件夹", LogLevel.Info);
            }
        }

        #endregion

        /// <summary>
        /// 通用API响应模型
        /// </summary>
        private class ApiResponse<T>
        {
            public bool Success { get; set; }
            public string Message { get; set; } = string.Empty;
            public T? Data { get; set; }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public  void Dispose()
        {
            // 取消事件订阅
            if (_eventsSubscribed)
            {
                _signalRService.ExportCompleted -= OnExportCompleted;
                _signalRService.NotificationReceived -= OnNotificationReceived;
                _signalRService.ConnectionStateChanged -= OnConnectionStateChanged;
            }
            
            _httpClient?.Dispose();
            _messageQueueService?.Dispose();
            _signalRService?.Dispose();
            base.Dispose();
        }
    }
}